#include "compile_run.hpp"
#include "../comm/httplib.h"

using namespace ns_compiler_and_run;
using namespace httplib;

void Usage(std::string proc)
{
    std::cerr << "Usage: " << "\n\t" << proc << "port" << std::endl;
}
// 编译服务随时可能被多人请求，必须保证传上来的code形成源文件名具有唯一性
// 不然多个用户之间会相互影响
// ./compile_server port
int main(int argc, char *argv[])
{
    //提供的编译服务，打包形成一个网络服务
    //cpp-httplib

    
    Server svr;

    svr.Get("/hello", [](const Request &req, Response &resp){
        resp.set_content("hello, httplib!", "text/plain;charset=utf-8");
    });

    svr.Post("/compile_and_run",[](const Request &req, Response &resp){
        //用户请求的服务正文是json string
        std::string in_json = req.body;
        std::string out_json;
        if(!in_json.empty()){
            CompileAndRun::Start(in_json, &out_json);
            resp.set_content(out_json, "application/json;charset=utf-8");
        }
    });
    svr.listen("0.0.0.0", atoi(argv[1])); //启动http服务
    


    /***************************************
     * in_json: {"code": "#include...", "input": "","cpu_limit":1, "mem_limit":10240}
     * out_json: {"status":"0", "reason":"出错原因","stdout":"","stderr":"",}
     * 通过http 让 client 上传一个json string
     ***************************************/

    //下面的工作充当客户端请求的json串
    std::string in_json;

    Json::Value in_value;
    //R"()" 在括号内的全部按照字符处理，不考虑特殊符号
    in_value["code"] = R"(#include<iostream>
    int main(){
        std::cout << "test1" << std::endl;
        return 0;
    })";

    in_value["input"] = "";
    in_value["cpu_limit"] = 1;
    in_value["mem_limit"] = 10240*3;

    Json::FastWriter writer;
    in_json = writer.write(in_value);

    std::cout << in_json << std::endl;
    std::string out_json;
    CompileAndRun::Start(in_json, &out_json);
    std::cout << out_json << std::endl;
    
    return 0;
}